<script lang="ts">
import { PropType, defineComponent, h, provide, ref, resolveComponent } from 'vue';

export default defineComponent({
  name: 'f-dy-array',
  props: {
    type: String,
    value: { type: Array as PropType<{ value: string; key: string }[]> },
    props: Object
  },
  emits: ['update:value', 'change'],
  setup: (props, { emit }) => {
    return () => {
      const Comp = resolveComponent('f-' + props.type);
      if (!Comp) return;
      const value = props.value ?? [];

      const notify = (value) => {
        emit('update:value', value);
        emit('change', value);
      };

      // 当数组为空时，添加一个空元素占位
      if (value.length === 0) {
        notify([{ key: Date.now(), value: '' }]);
      }

      return h(
        'div',
        { class: 'dy-table-array-input' },
        value.map((item, index) => {
          return h(
            'div',
            { class: ['dy-table-array-input-item h30', { mb4: index !== value.length - 1 }] },
            [
              h(Comp, {
                ...(props.props || {}),
                key: item.key,
                value: item.value,
                rowId: item.key,
                'onUpdate:value': (v) => {
                  const copy = value.map((item, i) => {
                    if (i === index) {
                      return { ...item, value: v };
                    }
                    return item;
                  });
                  notify(copy);
                }
              })
            ]
          );
        })
      );
    };
  }
});
</script>
